package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {

    @Autowired
    AliOssUtil aliOssUtil;


    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        log.info("OSS启用");
        try {
            //获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            //截取文件后缀名.substring字符串截取方法   lastIndexOf获取参数在string字符串里面最后出现位子的索引
            // 结合起来就是用字符串截取方法,加上字符串最后出现.位子的索引获取后缀名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            //给文件一个不会重复的新名.并且加上后缀名 用uuid.randomUUID()生成一个随机不重复的uuid,并转成字符串加上后缀名
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

}




